package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.ruoyi.system.mapper.SysWxUserMapper;
import com.ruoyi.system.domain.SysWxUser;
import com.ruoyi.system.service.ISysWxUserService;
import com.ruoyi.system.config.WxMaConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.util.Set;
import java.util.HashSet;

/**
 * 微信用户Service业务层处理
 */
@Service
public class SysWxUserServiceImpl implements ISysWxUserService {
    private static final Logger log = LoggerFactory.getLogger(SysWxUserServiceImpl.class);

    @Autowired
    private SysWxUserMapper wxUserMapper;

    @Autowired
    private WxMaConfig wxMaConfig;

    @Autowired
    private RestTemplate restTemplate;

    private static final String WX_CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 查询微信用户
     */
    @Override
    public SysWxUser selectWxUserById(Long userId) {
        return wxUserMapper.selectWxUserById(userId);
    }

    /**
     * 通过openid查询微信用户
     */
    @Override
    public SysWxUser selectWxUserByOpenid(String openid) {
        return wxUserMapper.selectWxUserByOpenid(openid);
    }

    /**
     * 查询微信用户列表
     */
    @Override
    public List<SysWxUser> selectWxUserList(SysWxUser wxUser) {
        return wxUserMapper.selectWxUserList(wxUser);
    }

    /**
     * 新增微信用户
     */
    @Override
    public int insertWxUser(SysWxUser wxUser) {
        wxUser.setCreateTime(DateUtils.getNowDate());
        return wxUserMapper.insertWxUser(wxUser);
    }

    /**
     * 修改微信用户
     */
    @Override
    public int updateWxUser(SysWxUser wxUser) {
        wxUser.setUpdateTime(DateUtils.getNowDate());
        return wxUserMapper.updateWxUser(wxUser);
    }

    /**
     * 批量删除微信用户
     */
    @Override
    public int deleteWxUserByIds(Long[] userIds) {
        return wxUserMapper.deleteWxUserByIds(userIds);
    }

    /**
     * 删除微信用户信息
     */
    @Override
    public int deleteWxUserById(Long userId) {
        return wxUserMapper.deleteWxUserById(userId);
    }

    /**
     * 微信登录
     */
    @Override
    public LoginUser wxLogin(String code) {
        try {
            log.info("开始微信登录，code: {}", code);
            log.info("当前配置 - AppID: {}", wxMaConfig.getAppid());
            
            // 1. 通过code获取openid
            String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    WX_CODE2SESSION_URL, wxMaConfig.getAppid(), wxMaConfig.getSecret(), code);
            
            log.info("请求微信接口URL: {}", url);
            
            String response = restTemplate.getForObject(url, String.class);
            log.info("微信接口返回结果: {}", response);
            
            JSONObject jsonObject = JSON.parseObject(response);
            
            // 检查是否有错误
            if (jsonObject.containsKey("errcode") && jsonObject.getIntValue("errcode") != 0) {
                String errorMsg = String.format("微信登录失败: %s (错误码: %d)", 
                    jsonObject.getString("errmsg"), 
                    jsonObject.getIntValue("errcode"));
                log.error(errorMsg);
                throw new RuntimeException(errorMsg);
            }
            
            String openid = jsonObject.getString("openid");
            String sessionKey = jsonObject.getString("session_key");
            String unionid = jsonObject.getString("unionid");
            
            log.info("获取到openid: {}", openid);
            
            // 2. 查询用户是否存在
            SysWxUser wxUser = selectWxUserByOpenid(openid);
            
            if (wxUser == null) {
                log.info("用户不存在，创建新用户");
                // 3. 用户不存在，创建新用户
                wxUser = new SysWxUser();
                wxUser.setOpenid(openid);
                wxUser.setUnionid(unionid);
                wxUser.setBindStatus("0"); // 未绑定
                insertWxUser(wxUser);
            }

            // 4. 创建LoginUser对象
            SysUser sysUser = new SysUser();
            sysUser.setUserId(wxUser.getUserId());
            sysUser.setUserName("wx_" + openid);
            sysUser.setNickName(wxUser.getNickname());

            LoginUser loginUser = new LoginUser();
            loginUser.setUserId(wxUser.getUserId());
            loginUser.setUser(sysUser);
            
            // 设置权限信息
            Set<String> permissions = new HashSet<>();
            permissions.add("wx:user");  // 添加微信用户基本权限
            loginUser.setPermissions(permissions);
            
            log.info("生成登录用户信息成功");
            
            return loginUser;
            
        } catch (Exception e) {
            log.error("微信登录处理异常", e);
            throw new RuntimeException("微信登录失败: " + e.getMessage());
        }
    }

    /**
     * 绑定微信用户到系统用户
     */
    @Override
    public int bindWxUser(SysWxUser wxUser, Long sysUserId) {
        wxUser.setSysUserId(sysUserId);
        wxUser.setBindStatus("1"); // 已绑定
        return updateWxUser(wxUser);
    }
} 